package com.xl98.config;

import com.xl98.entity.Permission;
import com.xl98.entity.Role;
import com.xl98.entity.User;
import com.xl98.mapper.RoleMapper;
import com.xl98.service.PermissionService;
import com.xl98.service.RoleService;
import com.xl98.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        try {

            List<Role> roles = roleService.selectRoleByUserId(user.getId());
            for (Role role : roles) {
                authorizationInfo.addRole(role.getName());//角色存储
            }
            //此处如果多个角色都拥有某项权限，不会数据重复，内部用的是Set
            List<Permission> permissions = permissionService.selectPermByRole(roles);
            for (Permission permission : permissions) {
                authorizationInfo.addStringPermission(permission.getName());//权限存储
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String) token.getPrincipal();
        HashMap<String, String> map = new HashMap<>();
        map.put("username",username);
        User user = userService.findByString(map);//*
        if (user == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getPassword(), //密码
                getName()
        );
        return authenticationInfo;
    }
}
